// pages/match/match.js
var match = require('../../utils/match');
Page({
  uploadImage(){
    var matchid = this.data.matchid;
    var index = this.data.index;
    var image = null;
    var time = new Date();
    var userid = this.data.userid;
    var username = this.data.username;
      var that = this;

      wx.chooseMedia({
          count: 1,
          success(res) {
              console.log(res.tempFiles)
              var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
              var ext = res.tempFiles[0].tempFilePath.slice(po)
              wx.cloud.uploadFile({
                  cloudPath: matchid + userid + index + ext,
                  filePath: res.tempFiles[0].tempFilePath,
                  success(res) {
                      console.log(res.fileID);
                      image = res.fileID;
                      var database = wx.cloud.database();
                      database.collection("itemScore").add({
                        data:{
                          matchid:matchid,
                          index:index,
                          image:image,
                          time:time,
                          userid:userid,
                          username:username
                        }
                      }).then((res)=>{
                        if(res){wx.showToast({
                          title: '图片上传成功',
                        });
                        //判断当前用户是否完成了整个比赛
                        database.collection("itemScore").where({
                          userid:that.data.userid,
                          matchid:that.data.matchid
                        }).get().then((b)=>{
                          //如果用户的分段完赛记录数量等于当前比赛的图片数组的长度则完成比赛
                          if(b.data.length==that.data.imageList.length){
                            //需要去完赛信息表添加一条记录
                            var matchid = that.data.matchid;
                            var matchname = that.data.matchname;
                            var userid = that.data.userid;
                            var username = that.data.username;
                            //到完赛信息表查询，获得当前用户的名次
                            database.collection("finalScore").where({
                              matchid:matchid
                            }).get().then((c)=>{
                              var len = c.data.length;
                              var mingci = len+1;
                              //获取当前用户在当前比赛的所有分段的完赛时间
                              database.collection("itemScore").where({
                                matchid:matchid,
                                userid:userid
                              }).get().then((d)=>{
                                var time = d.data[0].time;
                                for(let i=0;i<d.data.length;i++){
                                  if(d.data[i].time>time){
                                    time = d.data[i].time;
                                  }
                                }
                                //用完赛的最大时间减去比赛开始的时间，得到整个比赛的总用时
                                database.collection("match").where({
                                  _id:matchid
                                }).get().then((e)=>{
                                  matchname = e.data[0].title;
                                  var beginTime = e.data[0].beginTime;
                                  var shijiancha = time.getTime()-beginTime.getTime();
                                  var hours = Math.floor(shijiancha/(1000*60*60));
                                  var min = Math.floor(shijiancha%(1000*60*60)/(60000));
                                  var sec = Math.floor(shijiancha%(60000)/(1000));
                                  var haoshi = hours+"小时"+min+"分钟"+sec+"秒";
                                  database.collection("finalScore").add({
                                    data:{
                                      matchid:matchid,
                                      matchname:matchname,
                                      userid:userid,
                                      username:username,
                                      mingci:"第"+mingci+"名",
                                      shijiancha:shijiancha,
                                      haoshi:haoshi
                                    }
                                  }).then((f)=>{
                                    if(f)wx.showToast({
                                      title: '比赛完成了，您获得了第'+mingci+'名，比赛用时'+haoshi,
                                    })
                                    //判断当前是否为完成比赛的最后一个人，如果是的话则将前面整个小组的成绩加和
                                    
                                  });
                                })
                              });
                            });
                          }
                        })
                      }else{
                          wx.showToast({
                            title: '图片上传失败',
                          })
                        }
                      }).catch((err)=>{
                        wx.showToast({
                          title: '图片上传异常',
                        });
                        console.log(err);
                      });
                      that.setData({
                        currentImage:res.fileID
                      });
                  }
              })
          }
      })
  },
  click:function(e){
    this.setData({
      index : e.currentTarget.id
    });
    //查询数据库，获取切换分段后的完赛选手
    var that = this;
    var database = wx.cloud.database();
    database.collection("itemScore").where({
      matchid:that.data.matchid,
      index:that.data.index+""
    }).get().then((res)=>{
      for(let i=0;i<res.data.length;i++){
        var time = res.data[i].time;
        var d = time.toLocaleDateString().substring(0,10);
        var t = time.toTimeString().substring(0,8);
        time = d+" "+t;
        res.data[i].time = time;
      }
      that.setData({
        itemScore:res.data
      });
    });
    //判断当前用户在当前比赛分段是否已经完成
    database.collection("itemScore").where({
      userid:that.data.userid,
      matchid:that.data.matchid,
      index:that.data.index+""
    }).get().then((a)=>{
      if(a.data.length>0){
        that.setData({
          isWancheng:false
        });
      }else{
        that.setData({
          isWancheng:true
        });
      }
    });
  },
  daoda(){
    var k = this.data.index;
    this.setData({
      dialogShow:true,
      currentImage:this.data.imageList[k]
    });
  },
    /**
     * 页面的初始数据
     */
    data: {
      isWancheng:true,
      times:[],
      username:null,
      itemScore:[],
      currentImage:null,
      userid:null,
      matchid:null,
      title:null,
      imageList:[],
      picnames:[],
      index:0,
      category: 0,
      dialogShow:false,
      id: null,
      matches:match.list,
      little_location:"https://lbs.gtimg.com/visual/miniprogram-plugin/route-planning/assets/route_end.png"
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      //获取用户ID
      var that = this;
      wx.getStorage({
        key:"userid",
        success(res){
          that.setData({
            userid:res.data
          });
          var database = wx.cloud.database();
          database.collection("user").where({
            _id:that.data.userid
          }).get().then((r)=>{
            that.setData({
              username:r.data[0].name
            });
          })
          database.collection("baoming").where({
            userid:res.data
          }).get().then((msg)=>{
            that.setData({
              matchid:msg.data[0].matchid,
              tilte:msg.data[0].tilte
            });
            wx.setNavigationBarTitle({
              title: msg.data[0].title
            });
            //判断当前用户在当前比赛分段是否已经完成
            database.collection("itemScore").where({
              userid:that.data.userid,
              matchid:that.data.matchid,
              index:0+""
            }).get().then((a)=>{
              if(a.data.length>0){
                that.setData({
                  isWancheng:false
                });
              }
            });
            //获取该比赛对应的图片
            database.collection("match").where({
              _id:msg.data[0].matchid
            }).get().then((m)=>{
              that.setData({
                imageList:m.data[0].imageList
              });
              var picnames = [];
              for(let i=0;i<that.data.imageList.length;i++){
                var loc = that.data.imageList[i].lastIndexOf("/")
                var picname = that.data.imageList[i].slice(loc+1);
                loc = picname.lastIndexOf(".");
                picname = picname.slice(0,loc);
                picnames.push(picname);
              }
              that.setData({
                picnames:picnames
              });
            });
            //当前已经完成当前景点比赛的人员数组
            console.log("比赛ID："+that.data.matchid);
            console.log("比赛分段下标："+that.data.index);
            database.collection("itemScore").where({
              matchid:that.data.matchid,
              index:that.data.index+""
            }).get().then((s)=>{
              console.log("分项成绩的长度："+s.data.length);
              that.setData({
                itemScore:s.data
              });
              var times =[];
              for(let i=0;i<that.data.itemScore.length;i++){
                var time = that.data.itemScore[i].time;
                var t = time.toTimeString().substring(0,8);
                var d = time.toLocaleDateString().substring(0,10);
                time = d+" "+t;
                that.data.itemScore[i].time = time;
              }
              that.setData({
                itemScore:that.data.itemScore
              });
            })
          });
        }
      })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})